<template>
  <div class="container">
    <baleTable
      :tableData="tableData"
      :tableHead="tableHead"
      :isSearch="true"
      :tableLoading="tableLoading"
      :page="page"
      @pageSizeChange="pageSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @searchMethods="searchMethods"
      @tableSortChange="tableSortChange"
      @handleRowClick="handleRowClick"
      ref="baleTable"
    >
      <template #headLeft>
        <el-button
          class="mr10"
          type="primary"
          size="small"
          @click="nowRecords"
          :loading="nowBtnLoading"
          >立即备份</el-button
        >
        <span class="f14">自动备份：</span>
        <el-switch
          class="mr10"
          v-model="settingObj.status"
          active-color="#67C23A"
          @change="switchChange"
        >
        </el-switch>
        <el-popover
          placement="bottom"
          trigger="manual"
          v-model="settingObj.popover"
        >
          <el-tabs tab-position="left" v-model="settingObj.type">
            <el-tab-pane label="每天" name="day">
              <el-form label-width="50px">
                <el-form-item label="时间">
                  <el-time-picker
                    size="medium"
                    v-model="settingObj.day"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="时间"
                  >
                  </el-time-picker>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="每周" name="week">
              <el-form label-width="50px">
                <el-form-item label="周">
                  <el-select
                    v-model="settingObj.week"
                    size="medium"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="item in weekArr"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-time-picker
                    size="medium"
                    v-model="settingObj.day"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="时间"
                  >
                  </el-time-picker>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="每月" name="month">
              <el-form label-width="50px">
                <el-form-item label="月">
                  <el-select
                    v-model="settingObj.month"
                    size="medium"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="item in monthArr"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-time-picker
                    size="medium"
                    v-model="settingObj.day"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="时间"
                  >
                  </el-time-picker>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <div class="tx-r">
            <el-button size="medium" @click="settingObj.popover = false"
              >取 消</el-button
            >
            <el-button
              size="medium"
              type="primary"
              @click="settingSubmit"
              :loading="settingLoading"
              >确 定</el-button
            >
          </div>
          <el-button
            slot="reference"
            round
            size="medium"
            type="success"
            @click="settingObj.popover = true"
            >自动执行时间<i class="el-icon-arrow-down el-icon--right"
          /></el-button>
        </el-popover>
      </template>

      <template #file_path="{ scope }">
        <a
          style="color: blue"
          :href="$baseUrl + '/storage/' + scope.row.file_path"
          :download="scope.row.file_name"
          >点击下载备份数据</a
        >
      </template>

      <template #caozuo="{ scope }">
        <el-button type="primary" size="mini" @click="handle(scope.row, 1)"
          >恢复备份</el-button
        >
        <el-button type="danger" size="mini" @click="handle(scope.row, 2)"
          >删除</el-button
        >
      </template>
    </baleTable>
  </div>
</template>

<script>
import {
  ApibackupSetting,
  ApigetSetting,
  Apibackup,
  ApibackupRestore,
  ApibackupRestoreDel,
  ApibackupNow,
} from "@/api/index";
import { tableHead } from "./config";
import { debounce } from "@u/index";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      tableHead,
      tableData: [],
      page: {
        page: 1,
        size: 25,
        total: 0,
      },
      tableLoading: false,
      searchParams: {},
      sortParams: {},
      settedObj: {},
      settingObj: {
        status: false,
        week: null,
        month: null,
        day: null,
        popover: false,
        type: "day",
      },
      settingLoading: false,
      nowBtnLoading: false,
      weekArr: [
        { label: "星期一", value: 1 },
        { label: "星期二", value: 2 },
        { label: "星期三", value: 3 },
        { label: "星期四", value: 4 },
        { label: "星期五", value: 5 },
        { label: "星期六", value: 6 },
        { label: "星期天", value: 7 },
      ],
      monthArr: [],
    };
  },
  watch: {
    "settingObj.type"(value) {
      this.settingClear();
      if (value === this.settedObj.type) {
        this.settingObj = { ...this.settingObj, ...this.settedObj };
      }
    },
    "settingObj.popover"(flag) {
      if (!flag && !this.settedObj.status) {
        this.settingObj.status = false;
      }
    },
  },
  mounted() {
    this.getTableData();
    this.getSetting();
    for (let i = 1; i <= 31; i++) {
      this.monthArr.push({
        label: i + "号",
        value: i,
      });
    }
  },
  methods: {
    ...mapActions(["checkPermission"]),
    nowRecords() {
      this.nowBtnLoading = true;
      ApibackupNow({
        timeout: 1 * 60 * 60 * 1000,
      })
        .then((res) => {
          this.$message.success("立即备份成功！");
          this.getTableData();
          this.nowBtnLoading = false;
        })
        .catch(() => {
          this.$message.error("立即备份失败！");
          this.nowBtnLoading = false;
        });
    },
    handle(value, i) {
      let tip;
      let api;
      switch (i) {
        case 1:
          tip = "恢复";
          api = ApibackupRestore;
          break;
        case 2:
          tip = "删除";
          api = ApibackupRestoreDel;
          break;
      }
      this.$confirm(`此操作将${tip}该数据, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "加载中...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          api(value.id, {
            timeout: 1 * 60 * 60 * 1000,
          })
            .then((res) => {
              this.getTableData();
              this.$message({
                type: "success",
                message: tip + "成功!",
              });
            })
            .finally(() => {
              loading.close();
            });
        })
        .catch(() => {});
    },
    switchChange(flag) {
      if (!flag && this.settedObj.status) {
        ApibackupSetting({ status: false })
          .then((res) => {
            this.$message.success("已成功关闭自动备份数据！");
            this.settingClear();
            this.getSetting();
          })
          .catch(() => {
            this.settingObj.status = !flag;
            this.$message.error("关闭自动备份数据失败，请稍后重试！");
          });
      }
      this.$nextTick(() => {
        this.settingObj.popover = flag;
      });
    },
    settingClear() {
      this.settingObj.week = null;
      this.settingObj.month = null;
      this.settingObj.day = null;
    },
    getSetting(show) {
      // this.settingClear()
      this.checkPermission("获取自动备份").then((_) => {
        ApigetSetting()
          .then((res) => {
            const data = JSON.parse(res.data ?? "{}");
            this.settedObj = data;
            this.settingObj = { ...this.settingObj, ...data };
          })
          .finally(() => {
            if (show) this.settingObj.popover = false;
          });
      });
    },
    settingSubmit: debounce(
      function () {
        const { type, day, month, week } = this.settingObj;
        if (type === "month" && !month) {
          this.$message.error("请选择每月几号！");
          return;
        }
        if (type === "week" && !week) {
          this.$message.error("请选择周几！");
          return;
        }
        if (!day) {
          this.$message.error("请选择时间！");
          return;
        }
        this.settingLoading = true;
        const options = {
          status: true,
          day,
          month,
          week,
          type: type,
        };
        ApibackupSetting(options)
          .then((res) => {
            this.$message.success("已成功开启自动备份数据！");
            this.settingLoading = false;
            this.getSetting(true);
          })
          .catch(() => {
            //this.settingObj.status = false
            this.settingLoading = false;
            this.$message.error("开启自动备份数据失败，请稍后重试！");
          });
      },
      500,
      true
    ),
    getTableData(params = {}) {
      let postParams = {
        ...params,
        ...this.searchParams,
        ...this.sortParams,
        ...this.page,
      };
      this.tableLoading = true;
      Apibackup(postParams).then((res) => {
        let { data, page } = res;
        this.tableData = data;
        this.page.total = page.total;

        this.tableLoading = false;
      });
    },
    searchMethods(params) {
      this.searchParams = {};
      this.page.page = 1;
      this.searchParams = params;
      this.getTableData();
    },
    pageSizeChange(val) {
      this.page.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.page.page = val;
      this.getTableData();
    },
    tableSortChange(params) {
      if (params.sort_str) {
        this.sortParams = { ...this.sortParams, ...params };
      } else {
        delete this.sortParams.sort_str;
        delete this.sortParams.sort_order;
      }
      this.page.page = 1;
      this.getTableData();
    },
    handleRowClick(params) {},
  },
};
</script>

<style lang="less" scoped>
</style>
